package com.yuwj.chinaa.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yuwj.chinaa.R;
import com.yuwj.chinaa.base.BaseActivity;
import com.yuwj.chinaa.base.ConstantParam;
import com.yuwj.chinaa.entity.EntityOrderDetail;
import com.yuwj.chinaa.entity.EntityOrderWithTrade;
import com.yuwj.chinaa.presenter.IPresenter;
import com.yuwj.chinaa.presenter.presenterImpl.PresenterImpl;
import com.yuwj.chinaa.util.GlideImageLoader;
import com.yuwj.chinaa.util.PhoneUtil;
import com.yuwj.chinaa.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

//购买交易详情
public class TradeWithBuyDetailActivity extends BaseActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_trade_amount)
    TextView tvTradeAmount;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_tarde_state)
    TextView tvTradeState;
    @BindView(R.id.tv_trade_count)
    TextView tvTradeCount;
    @BindView(R.id.tv_tradeno)
    TextView tvTradeNo;
    @BindView(R.id.tv_match_tradeno)
    TextView tvMatchTradeNo;
    @BindView(R.id.tv_trade_tip)
    TextView tvTradeTip;
    @BindView(R.id.civ_user_photo)
    CircleImageView civUserPhoto;
    @BindView(R.id.tv_real_name)
    TextView tvRealName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_alipay_name)
    TextView tvAlipayName;
    @BindView(R.id.tv_alipay_account)
    TextView tvAlipayAccount;
    @BindView(R.id.tv_bankname)
    TextView tvBankName;
    @BindView(R.id.tv_bank_usernmae)
    TextView tvBankuserName;
    @BindView(R.id.tv_bank_account)
    TextView tvBankAccount;
    @BindView(R.id.ll_upload_img)
    LinearLayout llUploadImg;
    @BindView(R.id.iv_pay_pic)
    ImageView ivPayPic;
    @BindView(R.id.tv_uplaod_pic_tip)
    TextView tvPayPicTip;
    @BindView(R.id.rl_pay)
    RelativeLayout rlPay;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.ll_has_payed)
    LinearLayout llHasPayed;
    @BindView(R.id.ll_operator_container)
    LinearLayout llOperatorContainer;
    @BindView(R.id.tv_userno)
    TextView tvUserno;

    AlertDialog alertDialogWithShowQrCode;
    String orderId;
    EntityOrderDetail orderDetail;//交易买卖双方账户明细
    IPresenter presenter;
    NiceDialog niceDialogShowSelectPhoto;
    ImagePicker imagePicker;
    public int REQ_CODE_SELECT_IMAGE = 1;//拍照和选择图片的请求码

    @Override
    public int setCustomContentViewResourceId() {
        return R.layout.activity_trade_with_buy_detail;
    }

    public static Intent createIntent(Context context, String orderId) {
        Intent intent = new Intent(context, TradeWithBuyDetailActivity.class);
        intent.putExtra("orderId", orderId);
        return intent;
    }

    @Override
    public void initParam() {
        presenter = new PresenterImpl(this);
        orderId = getIntent().getStringExtra("orderId");
    }

    @Override
    public void initView() {
    }

    @Override
    public void initOperator() {
        JSONObject param = new JSONObject();
        try {
            param.put("orderId", orderId + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //卖家或买家查看订单明细
        presenter.queryOrderDetail(param.toString());
    }

    private void updatePayInfoView() {
        if (orderDetail != null) {
            tvTradeAmount.setText(orderDetail.getBiCountRMB() + " CNY");
            tvPrice.setText("价格：" + orderDetail.getBiPrice() + " CNY");
            tvTradeCount.setText("数量：" + orderDetail.getBiCount() + " china-A");

            tvTitle.setText("向" + orderDetail.getMatchingUserName() + "购买china-A");
            tvTradeNo.setText("订单号：" + orderDetail.getOrderNo());
            tvMatchTradeNo.setText("匹配单号：" + orderDetail.getOrderNo());
            Glide.with(context).load("").error(R.mipmap.ic_asset_user_photo).into(civUserPhoto);
            tvRealName.setText(orderDetail.getAuthUserName());
            tvPhone.setText(orderDetail.getMatchingUserPhone());
            tvUserno.setText(orderDetail.getMatchingUserNo());
            tvAlipayName.setText(orderDetail.getAuthUserName());
            tvAlipayAccount.setText(orderDetail.getAuthAliPayAccount());
            tvBankName.setText(orderDetail.getAuthBankName());
            tvBankuserName.setText(orderDetail.getAuthUserName());
            tvBankAccount.setText(orderDetail.getAuthBankNo());
            Glide.with(context).load(orderDetail.getPaySuccessImg() + "").placeholder(R.mipmap.ic_trade_add_pay_img).into(ivPayPic);

            switch (orderDetail.getPayStatus()) {
                case 0://未支付
                    tvTradeState.setText("待支付");
                    tvTradeTip.setText("china-A已托管,请在规定时间内完成付款,否则将自动取消");
                    if (!TextUtils.isEmpty(orderDetail.getPaySuccessImg())) {
                        tvPayPicTip.setText("已上传付款截图");
                        ivPayPic.setVisibility(View.VISIBLE);
                        llUploadImg.setVisibility(View.GONE);
                        tvPay.setText("我已付款");
                        tvPay.setBackgroundResource(R.mipmap.ic_trade_confirm_pay_btn_enable_bg);
                        rlPay.setEnabled(true);
                        llHasPayed.setVisibility(View.GONE);
                    } else {
                        tvPayPicTip.setText("上传一张付款截图");
                        ivPayPic.setVisibility(View.GONE);
                        llUploadImg.setVisibility(View.VISIBLE);
                        tvPay.setText("我已付款");
                        tvPay.setBackgroundResource(R.mipmap.ic_trade_confirm_pay_btn_unable_bg);
                        rlPay.setEnabled(false);
                        llHasPayed.setVisibility(View.GONE);
                    }
                    break;
                case 1://已支付
                    tvTradeState.setText("待支付");
                    tvTradeTip.setText("您已付款，等待对方确认并放币");
                    llUploadImg.setVisibility(View.GONE);
                    ivPayPic.setVisibility(View.VISIBLE);
                    tvPayPicTip.setText("已上传付款截图");
                    rlPay.setVisibility(View.GONE);
                    llHasPayed.setVisibility(View.VISIBLE);
                    llOperatorContainer.setVisibility(View.GONE);
                    break;
            }
        }

    }


    @OnClick({R.id.iv_back, R.id.ll_upload_img, R.id.rl_pay, R.id.rl_cancel, R.id.iv_make_call, R.id.iv_qrcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_upload_img:
                dialogShowPhotoSelect(this);
                break;
            case R.id.rl_cancel:
                JSONObject paramWithCancelTradingOrder = new JSONObject();
                try {
                    paramWithCancelTradingOrder.put("orderid", orderId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.cancelTradingOrder(paramWithCancelTradingOrder.toString());
                break;
            case R.id.rl_pay:
                JSONObject param = new JSONObject();
                try {
                    param.put("orderId", orderDetail.getOrderNo());
                    param.put("matchingOrderId", orderDetail.getMatchingOrderNo());
                    param.put("imgurl", orderDetail.getPaySuccessImg());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                presenter.payMoney(param.toString());
                break;
            case R.id.iv_make_call:
                PhoneUtil.makeCall(context, orderDetail.getMatchingUserPhone());
                break;
            case R.id.iv_qrcode:
                if (alertDialogWithShowQrCode == null) {
                    showDialogWithSetView();
                } else {
                    alertDialogWithShowQrCode.show();
                }
                break;

        }

    }

    /**
     * 弹框显示图片选择界面
     *
     * @param fragmentActivity
     */
    public void dialogShowPhotoSelect(final FragmentActivity fragmentActivity) {
        if (niceDialogShowSelectPhoto == null) {
            niceDialogShowSelectPhoto = NiceDialog.init();
            niceDialogShowSelectPhoto.setLayoutId(R.layout.content_userinfo_select_photo);
        }
        niceDialogShowSelectPhoto.setConvertListener(new ViewConvertListener() {
            @Override
            protected void convertView(ViewHolder viewHolder, final BaseNiceDialog baseNiceDialog) {

                TextView tvSelectPhoto = viewHolder.getView(R.id.tv_select_photo);
                TextView tvTakePhoto = viewHolder.getView(R.id.tv_take_photo);
                TextView tvCancel = viewHolder.getView(R.id.tv_cancel);
                View.OnClickListener onClickListener = new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_select_photo:
                                if (imagePicker == null) {
                                    imagePicker = ImagePicker.getInstance();
                                    imagePicker.setImageLoader(new GlideImageLoader());
                                    imagePicker.setMultiMode(false);
                                    imagePicker.setStyle(CropImageView.Style.RECTANGLE);
                                    imagePicker.setShowCamera(true);
                                    imagePicker.setCrop(false);
                                    imagePicker.setSaveRectangle(false);
                                    imagePicker.setSelectLimit(1);

                                    DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
                                    int screenWidth = curMetrics.widthPixels;
                                    int screenHeight = curMetrics.heightPixels;
                                    imagePicker.setFocusWidth(screenWidth / 2);
                                    imagePicker.setFocusHeight(screenHeight / 2);


                                }
                                Intent intent = new Intent(context, ImageGridActivity.class);
                                startActivityForResult(intent, REQ_CODE_SELECT_IMAGE);
                                break;
                            case R.id.tv_take_photo:
                                if (imagePicker == null) {
                                    imagePicker = ImagePicker.getInstance();
                                    imagePicker.setImageLoader(new GlideImageLoader());
                                    imagePicker.setMultiMode(false);
                                    imagePicker.setStyle(CropImageView.Style.CIRCLE);
                                    imagePicker.setShowCamera(true);
                                    imagePicker.setCrop(false);
                                    imagePicker.setSaveRectangle(false);
                                    imagePicker.setSelectLimit(1);
                                    DisplayMetrics curMetrics = context.getResources().getDisplayMetrics();
                                    int screenWidth = curMetrics.widthPixels;
                                    int screenHeight = curMetrics.heightPixels;
                                    imagePicker.setFocusWidth(screenWidth / 2);
                                    imagePicker.setFocusHeight(screenHeight / 2);

                                }
                                Intent intent2 = new Intent(context, ImageGridActivity.class);
                                intent2.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);//直接打开照相机
                                startActivityForResult(intent2, REQ_CODE_SELECT_IMAGE);
                                break;
                        }
                        baseNiceDialog.dismiss();
                    }
                };

                tvTakePhoto.setOnClickListener(onClickListener);
                tvSelectPhoto.setOnClickListener(onClickListener);
                tvCancel.setOnClickListener(onClickListener);
            }
        })
                .setDimAmount(0.3f)
                .setOutCancel(true)
                .setShowBottom(true);
        niceDialogShowSelectPhoto.show(fragmentActivity.getSupportFragmentManager());
    }


    void showDialogWithSetView() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.content_alipay_qrcode, null);
        ImageView ivQrcode = (ImageView) layout.findViewById(R.id.iv_alipay_qrcode);
        Bitmap bitmapWithQRCode = CodeUtils.createImage(orderDetail.getAuthAliPayAccount(), 400, 400, null);
        if (bitmapWithQRCode != null) {
            ivQrcode.setImageBitmap(bitmapWithQRCode);
        } else {
            ToastUtil.getInstance().shortLength(context, "二维码生成失败");
        }
        alertDialogWithShowQrCode = builder.setView(layout).create();
        alertDialogWithShowQrCode.setTitle("支付宝账号");
        alertDialogWithShowQrCode.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        alertDialogWithShowQrCode.setCancelable(true);//false-dialog弹出后会点击返回键，dialog不消失; true-点击返回键可消失;要想消失可以调用dismiss方法
        alertDialogWithShowQrCode.setCanceledOnTouchOutside(true);//false-点击对话框以外的区域,dialog不消失; true-点击对话框以外区域,dialog消失.
        //先调用show这个方法，然后才设置dialog的长宽
        alertDialogWithShowQrCode.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQ_CODE_SELECT_IMAGE) {
                File file = new File(ConstantParam.UPLOAD_COMPRESS_MEDIA_PATH);
                if (!file.exists()) {
                    file.mkdirs();
                }
                final ArrayList<ImageItem> imageItemList = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (imageItemList != null && imageItemList.size() > 0) {
                    ImageItem selectedImageItem = imageItemList.get(0);
                    String imgPath = selectedImageItem.path;
                    Luban.with(this)
                            .load(imgPath)                                   // 传入要压缩的图片列表
                            .ignoreBy(100)                                  // 忽略不压缩图片的大小
                            .setTargetDir(ConstantParam.UPLOAD_COMPRESS_MEDIA_PATH)                        // 设置压缩后文件存储位置
                            .setCompressListener(new OnCompressListener() { //设置回调
                                @Override
                                public void onStart() {
                                }

                                @Override
                                public void onSuccess(File file) {
                                    String filePath = file.getAbsolutePath();
                                    JSONObject param = new JSONObject();
                                    try {
                                        param.put("uploadtype", "1");//1.交易证明，2.头像上传

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    presenter.appUploadFilesImage(param.toString(), filePath);
                                }

                                @Override
                                public void onError(Throwable e) {
                                    ToastUtil.getInstance().shortLength(context, "压缩图片失败");
                                }
                            }).launch();    //启动压缩
                }
            } else {
                ToastUtil.getInstance().shortLength(context, "没有数据");
            }
        }
    }


    @Override
    public void onqueryOrderDetailSuccess(EntityOrderDetail orderDetail) {
        super.onqueryOrderDetailSuccess(orderDetail);
        this.orderDetail = orderDetail;
        updatePayInfoView();
    }


    @Override
    public void onqueryOrderDetailFail(Exception e) {
        super.onqueryOrderDetailFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage());
        llOperatorContainer.setVisibility(View.GONE);
    }

    @Override
    public void appUploadFilesImageSuccess(String imgUrl) {
        super.appUploadFilesImageSuccess(imgUrl);
        orderDetail.setPaySuccessImg(imgUrl);
        updatePayInfoView();
    }

    @Override
    public void appUploadFilesImageFail(Exception e) {
        super.appUploadFilesImageFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");
    }

    @Override
    public void onPayMoneySuccess() {
        super.onPayMoneySuccess();
        ToastUtil.getInstance().shortLength(context, "付款成功");
        JSONObject param = new JSONObject();
        try {
            param.put("orderId", orderId + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //卖家或买家查看订单明细
        presenter.queryOrderDetail(param.toString());
    }

    @Override
    public void onPayMoneyFail(Exception e) {
        super.onPayMoneyFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");

    }

    @Override
    public void onCancelTradingOrderSuccess() {
        super.onCancelTradingOrderSuccess();
        finish();
    }

    @Override
    public void onCancelTradingOrderFail(Exception e) {
        super.onCancelTradingOrderFail(e);
        ToastUtil.getInstance().shortLength(context, e.getMessage() + "");
    }
}
